package com.zlzlib.liblayoutmanager;

import android.view.animation.DecelerateInterpolator;
import android.widget.Scroller;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

/**
 * @Desc: 让中心对齐RecyclerView的工具类
 * @Copyright:
 * @DateTime: 2021/8/16 17:45
 * @Author zlz
 * @Version 1.0
 */
public class CenterSnapUtils extends RecyclerView.OnFlingListener {

    RecyclerView mRecyclerView;
    Scroller mGravityScroller;
    private boolean snapToCenter = false;

    /**
     * 绑定当前的recyclerView
     *
     * @param recyclerView 如果要解除绑定 就传null
     */
    public void attachToRecyclerView(@Nullable RecyclerView recyclerView) throws IllegalStateException {
        if (mRecyclerView == recyclerView) {
            return;
        }
        if (mRecyclerView != null) {
            destroyCallbacks();
        }
        mRecyclerView = recyclerView;
        if (mRecyclerView != null) {
            final RecyclerView.LayoutManager layoutManager = mRecyclerView.getLayoutManager();
            if (!(layoutManager instanceof BaseLayoutManager)) return;
            setupCallbacks();
            mGravityScroller = new Scroller(mRecyclerView.getContext(), new DecelerateInterpolator());
            snapToCenterView((BaseLayoutManager) layoutManager, ((BaseLayoutManager) layoutManager).getPageChangeListener());
        }
    }

    //滚动滑行的回调
    @Override
    public boolean onFling(int velocityX, int velocityY) {
        BaseLayoutManager layoutManager = (BaseLayoutManager) mRecyclerView.getLayoutManager();
        if (layoutManager == null) {
            return false;
        }
        RecyclerView.Adapter adapter = mRecyclerView.getAdapter();
        if (adapter == null) {
            return false;
        }
        if (!layoutManager.isInfiniteLoop() && (layoutManager.mOffset == layoutManager.getMaxOffset()
                        || layoutManager.mOffset == layoutManager.getMinOffset())) {
            return false;
        }
        final int minFlingVelocity = mRecyclerView.getMinFlingVelocity();
        mGravityScroller.fling(0, 0, velocityX, velocityY,
                Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE);
        if (layoutManager.mOrientation == BaseLayoutManager.VERTICAL && Math.abs(velocityY) > minFlingVelocity) {
            final int currentPosition = layoutManager.getCurrentPositionOffset();
            final int offsetPosition = (int) (mGravityScroller.getFinalY() / layoutManager.mInterval / layoutManager.getDistanceRatio());
            ScrollUtils.smoothScrollToPosition(mRecyclerView, layoutManager, layoutManager.getReverseLayout() ?
                    -currentPosition - offsetPosition : currentPosition + offsetPosition);
            return true;
        } else if (layoutManager.mOrientation == BaseLayoutManager.HORIZONTAL && Math.abs(velocityX) > minFlingVelocity) {
            final int currentPosition = layoutManager.getCurrentPositionOffset();
            final int offsetPosition = (int) (mGravityScroller.getFinalX() / layoutManager.mInterval / layoutManager.getDistanceRatio());
            ScrollUtils.smoothScrollToPosition(mRecyclerView, layoutManager, layoutManager.getReverseLayout() ?
                    -currentPosition - offsetPosition : currentPosition + offsetPosition);
            return true;
        }
        return true;
    }

    //通过监听滚动处理对齐
    private final RecyclerView.OnScrollListener mScrollListener = new RecyclerView.OnScrollListener() {

        boolean mScrolled = false;

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            final BaseLayoutManager layoutManager = (BaseLayoutManager) recyclerView.getLayoutManager();
            final PageChangeListener onPageChangeListener = layoutManager.getPageChangeListener();
            if (onPageChangeListener != null) {
                onPageChangeListener.onPageScrollStateChanged(newState);
            }
            if (newState == RecyclerView.SCROLL_STATE_IDLE && mScrolled) {
                mScrolled = false;
                if (!snapToCenter) {
                    snapToCenter = true;
                    snapToCenterView(layoutManager, onPageChangeListener);
                } else {
                    snapToCenter = false;
                }
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            if (dx != 0 || dy != 0) {
                mScrolled = true;
            }
        }
    };

    void destroyCallbacks() {
        mRecyclerView.removeOnScrollListener(mScrollListener);
        mRecyclerView.setOnFlingListener(null);
    }

    void setupCallbacks() throws IllegalStateException {
        if (mRecyclerView.getOnFlingListener() != null) {
            throw new IllegalStateException("已设置OnFlingListener的实例。");
        }
        mRecyclerView.addOnScrollListener(mScrollListener);
        mRecyclerView.setOnFlingListener(this);
    }

    void snapToCenterView(BaseLayoutManager layoutManager, PageChangeListener listener) {
        final int delta = layoutManager.getOffsetToCenter();
        if (delta != 0) {
            if (layoutManager.getOrientation() == BaseLayoutManager.VERTICAL)
                mRecyclerView.smoothScrollBy(0, delta);
            else
                mRecyclerView.smoothScrollBy(delta, 0);
        } else {
            snapToCenter = false;
        }
        if (listener != null) listener.onPageSelected(layoutManager.getCurrentPosition());
    }
}
